/*
 * Copyright (c) 2024 Black Sesame Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "dal_rticonnextdds/converter/InstanceHandleConverter.hpp"

InstanceHandleConverter* InstanceHandleConverter::singleton_ = nullptr;

InstanceHandleConverter::InstanceHandleConverter() {}

InstanceHandleConverter* InstanceHandleConverter::GetInstance()
{
    if (singleton_ == nullptr) {
        singleton_ = new InstanceHandleConverter();
    }
    return singleton_;
}

dal_ret_t
InstanceHandleConverter::ConvertInstanceHandleFromDalToRtidds(dal_instance_handle_t* d_ins,
                                                                  DDS_InstanceHandle_t* r_ins)
{
    if (r_ins == nullptr || d_ins == nullptr)
        return DAL_RETCODE_BAD_PARAMETER;
    memcpy(r_ins->keyHash.value, (uint8_t*)&d_ins->segment_0_, 4);
    memcpy(r_ins->keyHash.value + 4, (uint8_t*)&d_ins->segment_1_, 4);
    memcpy(r_ins->keyHash.value + 8, (uint8_t*)&d_ins->segment_2_, 4);
    memcpy(r_ins->keyHash.value + 12, (uint8_t*)&d_ins->segment_3_, 4);
    return DAL_RETCODE_OK;
}

dal_ret_t
InstanceHandleConverter::ConvertInstanceHandleFromRtiddsToDal(const DDS_InstanceHandle_t* r_ins,
                                                               dal_instance_handle_t* d_ins)
{
    if (r_ins == nullptr || d_ins == nullptr)
        return DAL_RETCODE_BAD_PARAMETER;
    memcpy(&d_ins->segment_0_, r_ins->keyHash.value, 4);
    memcpy(&d_ins->segment_1_, r_ins->keyHash.value + 4, 4);
    memcpy(&d_ins->segment_2_, r_ins->keyHash.value + 8, 4);
    memcpy(&d_ins->segment_3_, r_ins->keyHash.value + 12, 4);
    return DAL_RETCODE_OK;
}